// @webtoon/psd
// Copyright 2021-present NAVER WEBTOON
// MIT License

import {InvalidSliceOrigin} from "../../utils";
import {VersionedDescriptor} from "../Descriptor";
import {ImageResourceBlockBase} from "./ImageResourceBlockBase";
import {ResourceType} from "./ResourceType";

export type SlicesResourceBlock = ImageResourceBlockBase<
  ResourceType.Slices,
  SlicesResourceBlockV6 | SliceResourceBlockV7
>;

// Adobe Photoshop 6.0 and 7.0 use version === 6
// Adobe Photoshop CS and later use version === 7 or 8
// (Yes, this is confusing! Blame Adobe for this.)

interface SlicesResourceBlockV6 {
  /** Version used by Photoshop 6.0-7.0 */
  version: 6;
  /** Top of bounding rectangle for all the slices */
  boundTop: number;
  /** Left of bounding rectangle for all the slices */
  boundLeft: number;
  /** Bottom of bounding rectangle for all the slices */
  boundBottom: number;
  /** Right of bounding rectangle for all the slices */
  boundRight: number;
  sliceGroupName: string;
  slices: SliceEntry[];
  /**
   * Added in Photoshop 7.0
   * May or may not exist, depending on the size of the slice resource block.
   * This appears to store the duplicated contents of {@link slices}.
   */
  descriptor?: VersionedDescriptor;
}

export interface SliceEntry {
  id: number;
  groupId: number;
  origin: SliceOrigin;
  /** Exists only if `origin` is 1 */
  associatedLayerId?: number;
  name: string;
  type: number;
  left: number;
  top: number;
  right: number;
  bottom: number;
  url: string;
  target: string;
  message: string;
  altTag: string;
  isCellTextHtml: boolean;
  cellText: string;
  horizontalAlignment: number;
  verticalAlignment: number;
  /** Alpha color */
  alpha: number;
  red: number;
  green: number;
  blue: number;
}

/**
 * Describes how a slice was created.
 * @alpha
 */
export enum SliceOrigin {
  /**
   * Slice is automatically generated by Photoshop, from the areas remaining
   * after extracting the layer- and user-generated slices.
   */
  AutoGenerated = 0,
  /**
   * Slice is based on a layer's bounding box
   */
  LayerGenerated = 1,
  /**
   * Slice is created directly by the user
   */
  UserGenerated = 2,
}

export function matchSliceOrigin(origin: number): SliceOrigin {
  if (!(origin in SliceOrigin)) {
    throw new InvalidSliceOrigin(`Invalid slice origin: ${origin}`);
  }

  return origin;
}

interface SliceResourceBlockV7 {
  version: 7 | 8;
  descriptor: VersionedDescriptor;
}
